package com.lotter.api.controller;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.lotter.pay.Alipay;
import com.lotter.pay.AlipayCalReq;
/**
 * 支付
 * @author Administrator
 */
@Controller
@RequestMapping(value="/website/pay")
public class PayController {
	
	private static Logger logger = Logger.getLogger(PayController.class);
	
	/**
	 * 支付宝支付拉取
	 * @param request
	 * @param response
	 */
	@RequestMapping(value="/ali",method =RequestMethod.POST)
	public void pay(HttpServletRequest request, HttpServletResponse response){
		String totalStr = request.getParameter("total");
		 java.util.regex.Pattern pattern = java.util.regex.Pattern.compile("^(([1-9]{1}\\d*)|([0]{1}))(\\.(\\d){0,2})?$");  
         Matcher match = pattern.matcher(totalStr.trim());  
         if(match.matches()) {
			try {
				Alipay.pay(request, response,Double.parseDouble(totalStr),"测试","");
			} catch (Exception e) {
				logger.error("=---支付宝 回调异常---="+e);
			}
         }
	}
	
	

	/**
	 * 支付宝支付回调
	 * @param request
	 * @param response
	 */
	@RequestMapping(value="/alicalbk",method =RequestMethod.POST)
	public void alicalbk(HttpServletRequest request, HttpServletResponse response){
		AlipayCalReq calReq=null;
			try {
				calReq=Alipay.callbackReq(getParameterMap(request));
			} catch (Exception e) {
				logger.error("=---支付宝 回调异常---="+e);
			}
	}
	
	
	public Map<String,String> getParameterMap(HttpServletRequest request) {  
	    Map<String,String[]> properties = request.getParameterMap();  
	
	    // 返回值Map  
	
	    Map<String,String> returnMap = new HashMap<String,String>();  
	
	    Iterator<Entry<String, String[]>> entries = properties.entrySet().iterator();  
	
	    Map.Entry<String, String[]> entry;  
	
	    String name = "";  
	
	    String value = "";  
	
	    while (entries.hasNext()) {  
	
	        entry = (Map.Entry<String, String[]>) entries.next();  
	
	        name = (String) entry.getKey();  
	
	        Object valueObj = entry.getValue();  
	
	        if(null == valueObj){  
	
	            value = "";  
	
	        }else if(valueObj instanceof String[]){  
	
	            String[] values = (String[])valueObj;  
	
            for(int i=0;i<values.length;i++){  
	
                value = values[i] + ",";  
	
	            }  
	
	            value = value.substring(0, value.length()-1);  
	
	        }else{  
	
	            value = valueObj.toString();  
	
	        }  
	
	        returnMap.put(name, value);  
	
	    }  
	
	    return returnMap;  
	
	}  
	
}